package router

import (
	"myapp/config"
	"myapp/controllers"
	"myapp/middleware"
	"myapp/pkg"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRouter(db *gorm.DB) *gin.Engine {
	r := gin.Default()

	ossClient, err := pkg.NewOSSClient(
		config.Conf.OssEndpoint,
		config.Conf.OssAccessKeyID,
		config.Conf.OssAccessKeySecret,
		config.Conf.OssBucketName,
	)
	if err != nil {
		panic("OSS 初始化失败: " + err.Error())
	}

	r.Use(middleware.SetTranslator)

	// 公共路由
	r.POST("/login", controllers.Login(db))

	r.GET("/auth-session", controllers.AuthSession(db))
	r.POST("/phone-login", controllers.LoginWechat(db))

	r.GET("/public/home", controllers.HomeHandler(db))
	r.GET("/public/categories", controllers.NeedCategoriesHandler(db))
	r.GET("/public/needs", controllers.NeedListHandler(db))
	r.GET("/public/needs/:id", middleware.JWTAuthMiddlewarePublic(), controllers.NeedViewHandler(db))
	r.GET("/public/member/:id", middleware.JWTAuthMiddlewarePublic(), controllers.MemberViewHandler(db))
	r.GET("/public/member-categories", controllers.MemberCategoriesHandler(db))
	r.GET("/public/members", controllers.MemberListHandler(db))
	r.GET("/public/banner/:id", controllers.BannerViewHandler(db))
	r.GET("/public/trans-member", controllers.TransMemberHandler(db))
	r.GET("/public/article/:id", controllers.ArticleViewHandler(db))
	r.POST("/public/trans", controllers.TransHandler(db))

	// 需要认证的路由组
	authGroup := r.Group("/api")
	authGroup.Use(middleware.JWTAuthMiddleware())

	// 用户管理，只有拥有 user:create 权限的角色可以创建用户
	authGroup.POST("/users", middleware.RBACMiddleware(db, "user:create"), controllers.CreateUser(db))

	//r.GET("/test", controllers.TestHandler(db))

	// 文件上传，所有登录用户都可以
	authGroup.POST("/upload", controllers.UploadFileHandler(ossClient))

	authGroup.POST("/post", controllers.PostHandler(db))
	authGroup.POST("/join", controllers.JoinHandler(db))
	authGroup.POST("/join-union", controllers.JoinUnionHandler(db))
	authGroup.POST("/user-profile", controllers.ProfileHandler(db))
	authGroup.GET("/user-info", controllers.UserInfoHandler(db))
	authGroup.GET("/interests", controllers.InterestHandler(db))
	authGroup.GET("/my-needs", controllers.MyNeedsHandler(db))
	authGroup.GET("/my-needs/:id", controllers.MyNeedDelHandler(db))

	// 测试接口
	authGroup.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "pong"})
	})

	return r
}
